package cn.yuznu.www;

public class panduan {
    private static boolean shuzi(char ch){//判断数字
        return ch>='0'&&ch<='9';
    }
    private static int fuhao(char op){//判断符号
        if(op=='+'||op=='-') {
            return 0;
        }
        else if(op=='*'||op=='/') {
            return 1;
        }
        return -1;
    }

    private static int calculate(int num1,int num2,char op){
        switch (op){
            case '+':
                return num2+num1;
            case '-':
                return num2-num1;
            case '*':
                return num2*num1;
            case '/':
                return num2/num1;
            default:
                return 0;
        }
    }

    public static int zifuchuan(String expression){//读取字符串
        MyStack numStack=new MyStack(expression.length());//建立数字栈与操作栈
        MyStack opStack=new MyStack(expression.length());
        for(int i=0;i<expression.length();i++){//遍历字符串
            char ch=expression.charAt(i);
            if(shuzi(ch)){
                int num=0;
                while(i<expression.length()&&shuzi(expression.charAt(i))){//读取数字多少位
                    num=num*10+(expression.charAt(i++)-'0');
                }
                i--;
                numStack.push(num);
            }else{
                while(!opStack.isNULL()&&fuhao(ch)<=fuhao((char)opStack.peek())){
                    int num2=numStack.pop();
                    int num1=numStack.pop();
                    char op=(char)opStack.pop();
                    numStack.push(calculate(num1,num2,op));
                }
                opStack.push(ch);
            }
        }
        while(!opStack.isNULL()){//计算完
            int num1=numStack.pop();
            int num2=numStack.pop();
            char op= (char) opStack.pop();
            numStack.push(calculate(num1,num2,op));
        }
        return numStack.pop();
    }
}
